import * as http from 'http';
import * as https from 'https';
import * as vscode from 'vscode';
import * as os from 'os';
import { exec } from 'child_process';
import * as path from 'path';

const {
  generateKeyPairSync,
} = require('node:crypto')
const axios = require('axios');
const cheerio = require('cheerio');


export function isWindows(): boolean {
  return os.platform() === 'win32';
}

export function isLinux(): boolean {
  return os.platform() === 'linux';
}

export function isMacOS(): boolean {
  return os.platform() === 'darwin';
}


export function fetch(url: string): Promise<string> {
  // determine the library to use (based on the url protocol)
  const lib = url.startsWith('https://') ? https : http;

  return new Promise((resolve, reject) => {
    lib.get(url, (response) => {
      // make sure the status code is 200
      if (response.statusCode !== 200) {
        reject(new Error(`Failed to load page, status code: ${response.statusCode}`));
        return;
      }

      let data = '';
      response.on('data', (chunk) => {
        data += chunk;
      });
      response.on('end', () => {
        resolve(data);
      });
    }).on('error', (err) => {
      reject(err);
    });
  });
}

export const Sleep = (ms: number) => {
  return new Promise(resolve => setTimeout(resolve, ms))
}

export async function getVsCodeCommitId(): Promise<string> {
  if (isLinux() || isMacOS()) {
    return new Promise<string>((resolve) => {
      exec('code --version', (error, stdout, stderr) => {
        if (error) {
          console.error('Error occurred:' + error.message);
          resolve("");
          return;
        }
        if (stderr) {
          console.error('Error output:' + stderr);
          resolve("");
          return;
        }
        const lines = stdout.trim().split('\n');
        if (lines.length > 1) {
          const commitId = lines[1]; // 第二行是 commit ID
          resolve(commitId);
        } else {
          console.error('Unexpected output format:' + stdout);
          resolve("");
          return;
        }
      });
    })
  } else {
    // 获取vscode version
    const version = vscode.version

    // 根据version提取相应的release页面中的commitid
    try {
      const { data } = await axios.get(`https://github.com/microsoft/vscode/releases/tag/${version}`);

      // Load the HTML into cheerio
      const $ = cheerio.load(data);
      // Find the <a> tag with the 'data-hovercard-type="commit"' attribute
      const commitLink = $('a[data-hovercard-type="commit"]');
      // Extract the href attribute and commit hash
      const href = commitLink.attr('href'); // href example:  /microsoft/vscode/commit/fabdb6a30b49f79a7aba0f2ad9df9b399473380f
      const commitHash = href.split('/').pop();

      return commitHash
    } catch (error) {
      console.error('Failed to get commit id: ' + error)
      return ""
    }

  }
}

export function devstarDomain(): string | undefined {
  // 从用户配置中读取
  return vscode.workspace.getConfiguration('devstar').get('devstarDomain')
}

export async function showErrorNotification(message: string): Promise<void> {
  const selection = await vscode.window.showErrorMessage(message, 'Open Console', 'Report a problem',);
  if (selection === 'Open Console') {
    vscode.commands.executeCommand('workbench.action.toggleDevTools');
  } else if (selection === 'Report a problem') {
    vscode.commands.executeCommand('vscode.open', vscode.Uri.parse('https://github.com/mengning/DevStar/issues/new'));
  }
}

export async function powershellVersion(): Promise<string> {
  return new Promise((resolve, reject) => {
    exec('powershell -Command "$PSVersionTable.PSVersion.ToString()"', (error, stdout, stderr) => {
      if (error) {
        reject(`Error executing PowerShell command: ${error.message}`);
        return;
      }
      if (stderr) {
        reject(`PowerShell command returned an error: ${stderr}`);
        return;
      }
      resolve(stdout.trim());
    });
  });
}